<template>
  <div class="person-manager">
    <!-- 头像区域 -->
    <div class="avatar-section">
      <div class="avatar-wrapper">
        <img 
          v-if="userInfo.avatar" 
          :src="userInfo.avatar" 
          class="avatar-image"
          @click="handleAvatarClick"
        />
        <div v-else class="avatar-placeholder" @click="handleAvatarClick">
          <i class="el-icon-user"></i>
        </div>
        <div class="avatar-tip">点击修改头像</div>
      </div>
      <input 
        ref="avatarInput" 
        type="file" 
        accept="image/*" 
        style="display: none"
        @change="handleAvatarChange"
      />
    </div>

    <!-- 基本信息表单 -->
    <div class="info-section">
      <el-form :model="userInfo" label-position="left" label-width="90px">
        <el-form-item label="姓名">
          <el-input 
            v-model="userInfo.name" 
            placeholder="请输入姓名"
            :disabled="!isEditing"
          ></el-input>
        </el-form-item>

        <el-form-item label="手机号">
          <el-input 
            v-model="userInfo.phone" 
            placeholder="请输入手机号"
            :disabled="!isEditing"
            maxlength="11"
          ></el-input>
        </el-form-item>

        <el-form-item label="邮箱">
          <el-input 
            v-model="userInfo.email" 
            placeholder="请输入邮箱"
            :disabled="!isEditing"
          ></el-input>
        </el-form-item>

        <el-form-item label="性别">
          <el-radio-group v-model="userInfo.gender" :disabled="!isEditing">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="出生日期">
          <el-date-picker
            v-model="userInfo.birthday"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            :disabled="!isEditing"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>

        <el-form-item label="所在单位">
          <el-input 
            v-model="userInfo.organization" 
            placeholder="请输入所在单位"
            :disabled="!isEditing"
          ></el-input>
        </el-form-item>

        <el-form-item label="职务">
          <el-input 
            v-model="userInfo.position" 
            placeholder="请输入职务"
            :disabled="!isEditing"
          ></el-input>
        </el-form-item>

        <el-form-item label="工号">
          <el-input 
            v-model="userInfo.employeeId" 
            placeholder="请输入工号"
            :disabled="!isEditing"
          ></el-input>
        </el-form-item>

        <el-form-item label="个人简介">
          <el-input 
            v-model="userInfo.bio" 
            type="textarea"
            :rows="4"
            placeholder="请输入个人简介"
            :disabled="!isEditing"
            maxlength="200"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
    </div>

    <!-- 账号安全信息 -->
    <div class="security-section">
      <div class="section-title">账号安全</div>
      <div class="security-item" @click="handleChangePassword">
        <div class="security-label">
          <i class="el-icon-lock"></i>
          <span>修改密码</span>
        </div>
        <i class="el-icon-arrow-right"></i>
      </div>
      <div class="security-item">
        <div class="security-label">
          <i class="el-icon-time"></i>
          <span>最后登录</span>
        </div>
        <span class="security-value">{{ userInfo.lastLogin }}</span>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button 
        v-if="!isEditing" 
        type="primary" 
        size="large"
        @click="handleEdit"
      >
        编辑信息
      </el-button>
      <template v-else>
        <el-button 
          size="large"
          @click="handleCancel"
        >
          取消
        </el-button>
        <el-button 
          type="primary" 
          size="large"
          @click="handleSave"
        >
          保存
        </el-button>
      </template>
    </div>

    <!-- 修改密码对话框 -->
    <el-dialog
      title="修改密码"
      :visible.sync="passwordDialogVisible"
      width="90%"
      :close-on-click-modal="false"
      :before-close="handleClosePasswordDialog"
      custom-class="password-dialog"
    >
      <el-form 
        ref="passwordForm" 
        :model="passwordForm" 
        :rules="passwordRules"
        label-position="top"
      >
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input 
            v-model="passwordForm.oldPassword" 
            type="password"
            placeholder="请输入旧密码"
            show-password
            clearable
          ></el-input>
        </el-form-item>

        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="passwordForm.newPassword" 
            type="password"
            placeholder="6-20位，包含大小写字母和数字"
            show-password
            clearable
          ></el-input>
          <div class="password-tips">
            <i class="el-icon-info"></i>
            <span>密码必须包含大小写字母和数字，长度6-20位</span>
          </div>
        </el-form-item>

        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input 
            v-model="passwordForm.confirmPassword" 
            type="password"
            placeholder="请再次输入新密码"
            show-password
            clearable
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClosePasswordDialog">取消</el-button>
        <el-button type="primary" @click="handleConfirmChangePassword">确定修改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUserInfo, updateUserInfo, changePassword } from './service';

export default {
  name: 'PersonManager',

  data() {
    return {
      isEditing: false,
      userInfo: {
        avatar: '',
        name: '',
        phone: '',
        email: '',
        gender: '男',
        birthday: '',
        organization: '',
        position: '',
        employeeId: '',
        bio: '',
        lastLogin: ''
      },
      originalUserInfo: null, // 用于取消时恢复数据
      // 修改密码对话框
      passwordDialogVisible: false,
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      passwordRules: {
        oldPassword: [
          { required: true, message: '请输入旧密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度为6-20位', trigger: 'blur' },
          { 
            pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{6,20}$/, 
            message: '密码必须包含大小写字母和数字', 
            trigger: 'blur' 
          }
        ],
        confirmPassword: [
          { required: true, message: '请确认新密码', trigger: 'blur' },
          { 
            validator: (rule, value, callback) => {
              if (value !== this.passwordForm.newPassword) {
                callback(new Error('两次输入的密码不一致'));
              } else {
                callback();
              }
            }, 
            trigger: 'blur' 
          }
        ]
      }
    };
  },

  methods: {
    // 移动端Toast提示
    showToast(message, type = 'success') {
      this.$notify({
        title: '',
        message: message,
        type: type,
        duration: 2000,
        position: 'top-right',
        offset: 60,
        customClass: 'mobile-toast'
      });
    },

    // 点击头像
    handleAvatarClick() {
      if (!this.isEditing) {
        this.showToast('请先点击"编辑信息"按钮', 'info');
        return;
      }
      this.$refs.avatarInput.click();
    },

    // 头像文件变化
    handleAvatarChange(event) {
      const file = event.target.files[0];
      if (!file) return;

      // 验证文件类型
      if (!file.type.startsWith('image/')) {
        this.showToast('请选择图片文件', 'error');
        return;
      }

      // 验证文件大小（限制2MB）
      if (file.size > 2 * 1024 * 1024) {
        this.showToast('图片大小不能超过2MB', 'error');
        return;
      }

      // 读取文件并预览
      const reader = new FileReader();
      reader.onload = (e) => {
        this.userInfo.avatar = e.target.result;
        this.showToast('头像已更新，请保存信息');
      };
      reader.readAsDataURL(file);
    },

    // 编辑信息
    handleEdit() {
      this.isEditing = true;
      this.originalUserInfo = JSON.parse(JSON.stringify(this.userInfo));
    },

    // 取消编辑
    handleCancel() {
      this.$msgbox({
        title: '温馨提示',
        message: '确定要取消编辑吗？未保存的修改将会丢失',
        showCancelButton: true,
        confirmButtonText: '确定取消',
        cancelButtonText: '继续编辑',
        customClass: 'mobile-confirm-dialog',
        confirmButtonClass: 'mobile-confirm-btn',
        cancelButtonClass: 'mobile-cancel-btn',
        center: true,
        closeOnClickModal: false
      }).then(() => {
        this.userInfo = JSON.parse(JSON.stringify(this.originalUserInfo));
        this.isEditing = false;
      }).catch(() => {});
    },

    // 保存信息
    handleSave() {
      // 验证必填项
      if (!this.userInfo.name) {
        this.showToast('请输入姓名', 'error');
        return;
      }
      if (!this.userInfo.phone) {
        this.showToast('请输入手机号', 'error');
        return;
      }
      if (!/^1[3-9]\d{9}$/.test(this.userInfo.phone)) {
        this.showToast('请输入正确的手机号', 'error');
        return;
      }
      if (this.userInfo.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.userInfo.email)) {
        this.showToast('请输入正确的邮箱地址', 'error');
        return;
      }

      // 保存数据
      const loading = this.$loading({
        lock: true,
        text: '保存中...',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      updateUserInfo(this.userInfo).then(() => {
        loading.close();
        this.$notify({
          title: '✅ 保存成功',
          message: '个人信息已更新',
          type: 'success',
          duration: 2500,
          position: 'top-right',
          offset: 60,
          customClass: 'mobile-toast-large'
        });
        this.isEditing = false;
        this.originalUserInfo = JSON.parse(JSON.stringify(this.userInfo));
      }).catch(error => {
        loading.close();
        this.showToast(error.message || '保存失败，请稍后重试', 'error');
      });
    },

    // 修改密码
    handleChangePassword() {
      this.passwordDialogVisible = true;
      this.passwordForm = {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      };
    },

    // 关闭修改密码对话框
    handleClosePasswordDialog() {
      this.passwordDialogVisible = false;
      this.passwordForm = {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      };
      // 清除表单验证
      if (this.$refs.passwordForm) {
        this.$refs.passwordForm.clearValidate();
      }
    },

    // 确认修改密码
    handleConfirmChangePassword() {
      this.$refs.passwordForm.validate((valid) => {
        if (!valid) {
          return false;
        }

        const loading = this.$loading({
          lock: true,
          text: '修改中...',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        changePassword({
          oldPassword: this.passwordForm.oldPassword,
          newPassword: this.passwordForm.newPassword
        }).then(() => {
          loading.close();
          this.$notify({
            title: '✅ 修改成功',
            message: '密码已更新，请妥善保管',
            type: 'success',
            duration: 2500,
            position: 'top-right',
            offset: 60,
            customClass: 'mobile-toast-large'
          });
          this.handleClosePasswordDialog();
        }).catch(error => {
          loading.close();
          this.showToast(error.message || '修改失败，请稍后重试', 'error');
        });
      });
    },

    // 加载用户信息
    loadUserInfo() {
      const loading = this.$loading({
        lock: true,
        text: '加载中...',
        background: 'rgba(0, 0, 0, 0.7)'
      });

      getUserInfo().then(data => {
        this.userInfo = data;
        this.originalUserInfo = JSON.parse(JSON.stringify(data));
        loading.close();
      }).catch(error => {
        loading.close();
        this.showToast(error.message || '加载失败', 'error');
      });
    }
  },

  mounted() {
    this.loadUserInfo();
  }
};
</script>

<style scoped>
.person-manager {
  background: #f5f5f5;
  min-height: 100%;
  padding-bottom: 100px;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
}

/* 头像区域 */
.avatar-section {
  background: white;
  padding: 30px 0 35px;
  text-align: center;
  margin-bottom: 10px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.avatar-wrapper {
  display: inline-block;
}

.avatar-image,
.avatar-placeholder {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.3s;
}

.avatar-image {
  object-fit: cover;
  border: 3px solid #409EFF;
}

.avatar-placeholder {
  background: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 3px dashed #ddd;
}

.avatar-placeholder i {
  font-size: 50px;
  color: #ccc;
}

.avatar-image:active,
.avatar-placeholder:active {
  transform: scale(0.95);
}

.avatar-tip {
  margin-top: 12px;
  font-size: 13px;
  color: #999;
  font-weight: 400;
}

/* 信息表单区域 */
.info-section {
  background: white;
  padding: 20px 15px 10px;
  margin-bottom: 10px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.info-section >>> .el-form-item {
  margin-bottom: 22px;
}

.info-section >>> .el-form-item:last-child {
  margin-bottom: 10px;
}

.info-section >>> .el-form-item__label {
  color: #666;
  font-size: 14px;
}

.info-section >>> .el-input__inner {
  border-radius: 4px;
}

.info-section >>> .el-input.is-disabled .el-input__inner {
  background: #f8f8f8;
  color: #333;
}

.info-section >>> .el-textarea.is-disabled .el-textarea__inner {
  background: #f8f8f8;
  color: #333;
}

/* 账号安全区域 */
.security-section {
  background: white;
  padding: 15px;
  margin-bottom: 20px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.section-title {
  font-size: 15px;
  font-weight: 600;
  color: #333;
  margin-bottom: 10px;
  padding-left: 5px;
  border-left: 3px solid #409EFF;
  padding-left: 10px;
}

.security-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px 5px;
  border-bottom: 1px solid #f5f5f5;
  cursor: pointer;
  transition: background 0.3s;
}

.security-item:last-child {
  border-bottom: none;
  cursor: default;
}

.security-item:first-child:active {
  background: #f8f8f8;
}

.security-label {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #333;
}

.security-label i {
  margin-right: 8px;
  font-size: 18px;
  color: #409EFF;
}

.security-value {
  font-size: 13px;
  color: #999;
}

/* 操作按钮 */
.action-buttons {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 15px;
  box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  gap: 10px;
  z-index: 100;
  border-top: 1px solid #f0f0f0;
}

.action-buttons .el-button {
  flex: 1;
  border-radius: 6px;
  font-size: 15px;
  height: 46px;
  font-weight: 500;
}

/* 修改密码对话框 */
.password-dialog >>> .el-dialog {
  border-radius: 12px;
  max-width: 400px;
}

.password-dialog >>> .el-dialog__header {
  padding: 20px 20px 15px;
  border-bottom: 1px solid #f0f0f0;
}

.password-dialog >>> .el-dialog__title {
  font-size: 17px;
  font-weight: 600;
  color: #333;
}

.password-dialog >>> .el-dialog__body {
  padding: 25px 20px 20px;
}

.password-dialog >>> .el-form-item__label {
  font-size: 14px;
  color: #666;
  font-weight: 500;
  padding-bottom: 8px;
}

.password-dialog >>> .el-input__inner {
  height: 42px;
  border-radius: 6px;
  font-size: 14px;
}

.password-tips {
  display: flex;
  align-items: flex-start;
  margin-top: 8px;
  padding: 8px 10px;
  background: #f0f7ff;
  border-radius: 4px;
  font-size: 12px;
  color: #409EFF;
  line-height: 1.5;
}

.password-tips i {
  margin-right: 6px;
  margin-top: 1px;
  flex-shrink: 0;
}

.password-tips span {
  flex: 1;
}

.dialog-footer {
  display: flex;
  gap: 10px;
  padding: 15px 0 0;
}

.dialog-footer .el-button {
  flex: 1;
  height: 42px;
  border-radius: 6px;
  font-size: 15px;
}

/* 移动端优化 */
@media screen and (max-width: 768px) {
  .password-dialog >>> .el-dialog {
    margin: 0 auto !important;
    margin-top: 20vh !important;
  }
}

</style>

